package logic

import (
	"context"
	"errors"
	"real-check/models/cache"
	"real-check/models/mysql"
	"real-check/pkg"

	"real-check/checkrpc/checkrpc"
	"real-check/checkrpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
	"gorm.io/gorm"
)

type RegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterLogic {
	return &RegisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *RegisterLogic) Register(in *checkrpc.RegisterRequest) (*checkrpc.RegisterResponse, error) {
	// todo: add your logic here and delete this line

	result, _ := cache.Rdb.Get(l.ctx, "sms"+in.Username).Result()
	if result != in.Sms {
		return nil, errors.New("短信验证码错误")
	}

	var users mysql.User
	if err := users.FindName(mysql.DB, in.Username); err == nil {
		return nil, errors.New("用户名已存在")
	}
	user := mysql.User{
		Model:    gorm.Model{},
		Username: in.Username,
		Password: pkg.Md5(in.Password),
	}
	if err := user.Register(mysql.DB); err != nil {
		return nil, err
	}
	return &checkrpc.RegisterResponse{
		UserId: int64(user.ID),
	}, nil
}
